/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-07-21 16:13:51
 * @LastEditTime: 2023-06-02 14:17:52
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 文件处理
 * @FilePath: \vue3-element-plus-web\src\utils\fs.js
 * @Copyright 版权声明
 */

export const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

/**
 * 获取文件 扩展名
 * @param {String} filename
 * @returns
 */
export const getFileExtension = (filename) => {
  return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2)
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export const resolveBlob = (res, mimeType) => {
  const blob = new Blob([res.data])
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  if (result === null) {
    result = contentDisposition.match(
      /filename=(.*)/
    )
  }
  // console.log('contentDisposition--', contentDisposition)
  // console.log('reuslt--', result)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  //后台再header中传文件名
  const name = fileName
  downloadElement.href = href
  downloadElement.download = name
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}
